import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import * as mongoose from 'mongoose';

export type UserDocument = User & Document;

export enum UserRole {
    USER = 'user',
    CREATOR = 'creator',
    ADMIN = 'admin',
}

@Schema({
    timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
    toJSON: {
        transform: (_, ret) => {
            ret.id = ret._id;
            delete ret._id;
            delete ret.__v;
            delete ret.password; // 确保密码不会被返回
            return ret;
        }
    }
})
export class User extends Document {
    @Prop({ required: true, unique: true })
    username: string;

    @Prop({ required: true, unique: true })
    email: string;

    @Prop({ required: true })
    password: string;

    @Prop({ default: '' })
    avatar: string;

    @Prop({ default: '' })
    nickname: string;

    @Prop({ default: '' })
    bio: string;

    @Prop({ type: [String], enum: Object.values(UserRole), default: [UserRole.USER] })
    roles: UserRole[];

    @Prop({ default: false })
    email_verified: boolean;

    @Prop({ sparse: true, unique: true })
    phone: string;

    @Prop({ default: false })
    phone_verified: boolean;

    @Prop({ sparse: true, unique: true })
    wechat_openid: string;

    @Prop({ sparse: true, unique: true })
    wechat_unionid: string;

    @Prop({ type: mongoose.Schema.Types.Mixed, default: {} })
    preferences: any;

    @Prop({ type: [String], default: [] })
    favorited_works: string[]; // 存储收藏作品的ID

    @Prop()
    created_at: Date;

    @Prop()
    updated_at: Date;

    // 用户模型方法
    hasRole(role: UserRole): boolean {
        return this.roles.includes(role);
    }
}

export const UserSchema = SchemaFactory.createForClass(User);

// 添加实例方法
UserSchema.methods.hasRole = function (role: UserRole): boolean {
    return this.roles.includes(role);
}; 